<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;

/**
 * 库存预警管理
 *
 * @icon fa fa-exclamation-triangle
 * @remark 管理库存预警记录和处理
 */
class Stockalert extends Backend
{
    /**
     * Stockalert模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('scanwork_stock_alert_log');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->alias('a')
                ->join('scanwork_material m', 'a.material_id = m.id')
                ->join('scanwork_warehouse w', 'a.warehouse_id = w.id', 'LEFT')
                ->field('a.*, m.code as material_code, m.name as material_name, m.spec, w.warehouse_name')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $total = $this->model
                ->alias('a')
                ->join('scanwork_material m', 'a.material_id = m.id')
                ->join('scanwork_warehouse w', 'a.warehouse_id = w.id', 'LEFT')
                ->where($where)
                ->count();

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 处理预警
     */
    public function handle($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $this->model->where('id', $ids)->update([
                        'is_handled' => 1,
                        'handler_id' => $this->auth->id,
                        'handle_time' => time(),
                        'handle_remark' => $params['handle_remark'] ?? ''
                    ]);
                    Db::commit();
                    $this->success();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $row = $this->model->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}

